<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 二叉树实现结构
        function Node(value) {
            this.value = value;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(null)
        var c = new Node(2)
        var d = new Node(3)
        a.left = b
        a.right = c
        b.left = d
        // 后序遍历-迭代法
        var postorderTraversal = function (root, res = []) {
            if (!root) return []
            let stack = []
            // 根节点先放进去
            stack.push(root)
            // 如下是中-> 右 => 左，反转后就是 左右中
            while (stack.length) {
                // 弹出节点，放到栈中
                let cur = stack.pop()
                res.push(cur.value)
                // 左节点入栈
                cur.left && stack.push(cur.left)
                // 右节点入栈
                cur.right && stack.push(cur.right)
            }
            return reverseArray(res)
        }

        function reverseArray(arr) {
            let left = 0
            let right = arr.length - 1
            while (left <= right) {
                let temp = arr[left]
                arr[left] = arr[right]
                arr[right] = temp
                left++
                right--
            }
            return arr
        }
        console.log(postorderTraversal(a), 'postorderTraversal(a)');



    </script>
</body>

</html>